package com.arrogames.rgblabyrinth {
	
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.display3D.Context3DRenderMode;
	import flash.events.Event;
	import flash.geom.Rectangle;
	
	import org.as3commons.logging.api.ILogger;
	import org.as3commons.logging.api.LOGGER_FACTORY;
	import org.as3commons.logging.api.getLogger;
	import org.as3commons.logging.setup.LogSetupLevel;
	import org.as3commons.logging.setup.RegExpSetup;
	import org.as3commons.logging.setup.target.TraceTarget;
	
	import starling.core.Starling;
	import starling.events.Event;
	import starling.events.ResizeEvent;
	import starling.utils.RectangleUtil;
	import starling.utils.ScaleMode;
	
	[SWF(width="800", height="600", frameRate="60")]
	[Frame(factoryClass="com.arrogames.rgblabyrinth.preloader.RGBPreloader")]
	public class Main extends Sprite {
		private static const logger:ILogger = getLogger(Main);
		
		public static const WIDTH:Number = 800;
		public static const HEIGHT:Number = 600;
				
		private var myStarling:Starling;
		private var myGame:RGBLabyrinth;
			
		public function Main() {
			if (stage) init();
			else addEventListener(flash.events.Event.ADDED_TO_STAGE, init);
		}
		
		private function init(event:flash.events.Event = null):void {
			removeEventListener(flash.events.Event.ADDED_TO_STAGE, init );
			
			var logTarget:TraceTarget = new TraceTarget();
			LOGGER_FACTORY.setup = new RegExpSetup()
                              .addTargetRule( /^com\.arrogames\./, logTarget, LogSetupLevel.DEBUG );
			
			// support autoOrients
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			
			Starling.handleLostContext = true;
			
			var stageWidth:int  = WIDTH;
			var stageHeight:int = HEIGHT;
				
			//viewport to make the stage as big as possible and of proper scale on all devices
			var viewPort:Rectangle = RectangleUtil.fit(
				new Rectangle(0, 0, stageWidth, stageHeight), 
				new Rectangle(0, 0, stage.stageWidth, stage.stageHeight), 
				ScaleMode.SHOW_ALL);
			
			myStarling = new Starling( RGBLabyrinth, stage, viewPort, null, Context3DRenderMode.AUTO, "baseline");
			myStarling.stage.stageWidth = stageWidth;
			myStarling.stage.stageHeight = stageHeight;
			myStarling.showStats = true;
			myStarling.showStatsAt("right", "bottom");
			
			resizeViewPort();
			
			myStarling.start();
			myStarling.addEventListener(starling.events.Event.ROOT_CREATED, onRootCreated);
			stage.addEventListener(flash.events.Event.DEACTIVATE, stageDeactivateHandler, false, 0, true);
		}
		
		private function onRootCreated(event:starling.events.Event, game:RGBLabyrinth):void {
			logger.debug("Root Created");
			this.myGame = game;
			
			myStarling.removeEventListener(starling.events.Event.ROOT_CREATED, onRootCreated);
			myStarling.stage.addEventListener(ResizeEvent.RESIZE, onResize);
			
			AssetManager.instance.enqueueAll();
			AssetManager.instance.loadQueue(onProgress);
		}
		
		private function onProgress(ratio:Number):void {
			logger.debug("Loading assets, progress: {0}%", [ratio*100]);
			myGame.updateAssetProgress(ratio);
			
			if (ratio == 1) {
				myGame.loadingComplete();
			}
		}
		
		private function stageDeactivateHandler(event:flash.events.Event):void {
			logger.debug("Stage Deactivated");
			this.myStarling.stop();
			this.stage.addEventListener(flash.events.Event.ACTIVATE, stageActivateHandler, false, 0, true);
		}
		
		private function stageActivateHandler(event:flash.events.Event):void {
			logger.debug("Stage Activated");
			this.stage.removeEventListener(flash.events.Event.ACTIVATE, stageActivateHandler);
			this.myStarling.start();
		}
		
		private function onResize(e:starling.events.Event):void {
			resizeViewPort();
		}
		
		private function resizeViewPort():void {
			// set rectangle dimensions for viewPort:
			var viewPortRectangle:Rectangle = new Rectangle();
			viewPortRectangle.width = stage.stageWidth;
			viewPortRectangle.height = stage.stageHeight;
			Starling.current.viewPort = viewPortRectangle;
		}
	}
}